package com.suneee.ep.proxy.servlet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suneee.ep.proxy.api.ApiData;
import com.suneee.ep.proxy.api.ProxyData;
import com.suneee.ep.proxy.utils.Http;
import com.suneee.ep.proxy.utils.Utils;

@WebServlet(name="proxy",urlPatterns={"/px.do"},loadOnStartup=1)
public class ProxyServlet extends HttpServlet { 
	private static final long serialVersionUID = 1L;
	private static Logger log =LoggerFactory.getLogger(ProxyServlet.class);
	
	private String signValue="suneee-api-eportal";
	
	public void init() throws ServletException {
		//
    }
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp){
		writeSucess(resp,"系统当前时间为-"+new Date()+",i am "+ this );
	}
	                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
	public void doPost(HttpServletRequest req, HttpServletResponse resp){
		String ip=req.getRemoteAddr();
		String sign=req.getParameter("sign");
		String data=req.getParameter("data");
		if(data==null){
			ProxyData p=readProxyData(req);	
			sign=p.getSign();
			data=p.getData();
		}
		
		log.debug("request from ip={},sign={},data={}",ip,sign,data);
		
		String s=Utils.md5(data+signValue);
		if(s.equals(sign)==false){
			log.info("非法访问,ip={},sign={},data={}",ip,sign,data);
			return;
		}
		ApiData r=null;
		
		try {
			r=Utils.decode(data);
			log.debug("请求的数据:{}",Utils.toJson(r));
		} catch (Exception e) {
			log.error("获取请求内容异常", e);
		}
		if(r==null){
			writeFail(resp,"请求数据验证错误");
			return;
		}
				
		String rs=proxyApi(r);
		try { 
			data=Utils.encode(rs,2,5); 
			writeSucess(resp,data);
		} catch (Exception e) {
			log.error("获取请求内容异常", e);
			writeFail(resp,"处理异常");
			return;
		}
			
	}
	
	private String proxyApi(ApiData r){
		Map<String, Object> m=r.getBody();
		TreeMap<String,String> ps=Utils.convert(m);
		String url=r.getUrl();
		String rets=Http.doPostData(url,ps);
		return rets;
	}

	private void writeSucess(HttpServletResponse res,String ms){
		
		res.setContentType("text/html;charset=utf-8");
        res.setCharacterEncoding("utf-8");
        
		ProxyData p=new ProxyData();		
		p.setStatus("success"); 
		p.setDesc("成功处理");
		p.setData(ms);
		
		String msg=Utils.toJson(p);
		
		try{
			log.debug("return sucess:{}",msg);
			res.getWriter().write(msg);
			res.flushBuffer();
		}catch(Exception e){
			log.error("写返回值异常", e);
		}
	}
	
	private void writeFail(HttpServletResponse res,String ms){
		res.setContentType("text/html;charset=utf-8");
        res.setCharacterEncoding("utf-8");
        
		ApiData a=new ApiData();
		a.setStatus("fail");
		a.setDesc(ms);
		ProxyData p=new ProxyData();		
		String msg=Utils.toJson(a);
		p.setData(msg);
		try{
			log.debug("return fail:{}",msg);
			msg=Utils.toJson(p);
			res.getWriter().write(msg);
			res.flushBuffer();
		}catch(Exception e){
			log.error("写返回值异常", e);
		}
	}
		
	
	private ProxyData readProxyData(HttpServletRequest req){
		try{
			StringBuilder sb=new StringBuilder();
			InputStreamReader in = new InputStreamReader(req.getInputStream());
			BufferedReader br=new BufferedReader(in);
			String line=br.readLine();
			while(line!=null){
				sb.append(line);
				line=br.readLine();
			}
			br.close();
			in.close();
			log.debug("request,body="+sb.toString());
			
			ProxyData p=Utils.parseJson(sb.toString(), ProxyData.class);
			return p;
		}catch(Exception e){
			log.info("读取Request异常",e);
		}
		return null;
	}
	
}
